package sharetime.playlist.controllers;

import java.beans.PropertyEditorSupport;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sharetime.tag.domain.Tag;
import sharetime.tag.service.ITagManager;
import sharetime.util.SpringBeanUtils;

public class TagsPropertyEditor extends PropertyEditorSupport {

	private static final String DEFAULT_SEPARATOR = ",";

	private static final Logger logger = LoggerFactory
			.getLogger(TagsPropertyEditor.class);

	private ITagManager tagManager;

	public TagsPropertyEditor() {
		tagManager = (ITagManager) SpringBeanUtils.getBean("tagManager");
	}

	@Override
	public void setAsText(String text) {
		logger.debug("entering setAsText method...");
		logger.debug("text is: " +text);
		String[] tags = text.split(DEFAULT_SEPARATOR);
		List<Tag> tagList = new ArrayList<Tag>();
		for (int i = 0; i < tags.length; i++) {
			String tagName = tags[i];
			Tag tag = tagManager.getTagByName(tagName);
			if (tag == null) {
				tag = new Tag(tagName);
				tagManager.saveTag(tag);
			}
			tagList.add(tag);
		}
		setValue(tagList);
	}

	@SuppressWarnings("unchecked")
	@Override
	public String getAsText() {
		logger.debug("entering getAsText method...");
		List<Tag> tags = (List<Tag>) getValue();
		if (null == tags) {
			return "";
		}
		StringBuilder sb = new StringBuilder("");
		for (int i = 0; i < tags.size(); i++) {
			sb.append(tags.get(i).getName());
			if (i > 0) {
				sb.append(DEFAULT_SEPARATOR);
			}
		}
		logger.debug("build tag string: " + sb.toString());
		return sb.toString();
	}
}
